/**
 *
 */
package com.hsd.whb.security.recorder;

import com.hsd.whb.repository.RecorderRepository;
import com.hsd.whb.security.HwbManagerUserDetailsService;
import com.hsd.whb.security.HwbRecorderUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author zhailiang
 */
@Component
public class RecorderAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler hwbAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler hwbAuthenticationFailureHandler;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RecorderRepository recorderRepository;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        RecorderAuthenticationFilter recorderAuthenticationFilter = new RecorderAuthenticationFilter();
        recorderAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        recorderAuthenticationFilter.setAuthenticationSuccessHandler(hwbAuthenticationSuccessHandler);
        recorderAuthenticationFilter.setAuthenticationFailureHandler(hwbAuthenticationFailureHandler);

        RecorderAuthenticationProvider recorderAuthenticationProvider = new RecorderAuthenticationProvider();
        recorderAuthenticationProvider.setUserDetailsService(new HwbRecorderUserDetailsService(recorderRepository));
        recorderAuthenticationProvider.setPasswordEncoder(passwordEncoder);

        http.authenticationProvider(recorderAuthenticationProvider)
                .addFilterAfter(recorderAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }

}
